package com.tianxiabuyi.utils;

import com.tianxiabuyi.model.pojo.HospitalLabel;
import com.tianxiabuyi.persist.QBuilder;
import com.tianxiabuyi.persist.Where;

import java.util.*;

/**
 * 通讯录标签相关
 */
public final class LabelUtil {

    /**
     * 自定义标签
     */
    public static final Integer ZERO = 0;

    /**
     * 获取标签类
     * @param hospital
     * @param type: 0: 全部标签类, 1: 默认标签类, 2: 自定义标签类
     * @return
     */
    public static Map<String, List<Map>> getLabelClass(Integer hospital, Integer type) {
        Map<String, List<Map>> returnMap = new HashMap<String, List<Map>>();
        if (hospital == null) {
            return returnMap;
        }
        type = Tools.getInt(type, ZERO);
        if (type != 1) {
            List<Map> customizeList = QBuilder.db("basedb").select("new map(id as id, name as name)").from("HospitalLabel").where(new Where("hospital=", hospital).and("status=", ConstantUtil.STATUS_ENABLE).and("category=", ZERO)).order("id", "asc").query().getResultObj();
            returnMap.put("customize", customizeList);
        }
        if (type != 2) {
            List<Map> defaultList = QBuilder.db("basedb").select("new map(id as id, name as name)").from("HospitalLabelCategory").where(new Where("hospital=0 or hospital=", hospital).and("status=", ConstantUtil.STATUS_ENABLE)).order("id", "asc").query().getResultObj();
            returnMap.put("base", defaultList);
        }
        return returnMap;
    }

    /**
     * 根据标签类查看子标签
     * @param hospital
     * @param labelCategory: 0: 查全院
     * @return
     */
    public static List<Map> getLabel(Integer hospital, Integer labelCategory) {
        List<Map> returnList = null;
        if (hospital == null) {
            return returnList;
        }
        labelCategory = Tools.getInt(labelCategory, ZERO);
        Where where = new Where();
        if (labelCategory != 0) {
            where.and("hlc.id=", labelCategory);
        }
        returnList = QBuilder.db("basedb").select("new map(hl.id as label_id, hl.name as label_name)").from("HospitalLabel hl, HospitalLabelCategory hlc").where(where.and("hl.category=hlc.id").and("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hlc.hospital=", "0").and("hlc.status=", ConstantUtil.STATUS_ENABLE)).order("hlc.id asc, hl.id asc", "").query().getResultObj();
        if (returnList == null || returnList.isEmpty()) {
            return returnList;
        }
        List<Map> countList = getCountInLabel(hospital, 0);
        if (countList == null) {
            countList = new ArrayList<Map>();
        }
        for (Map returnMap : returnList) {
            boolean flag = false;
            Integer id = Tools.getInt(returnMap.get("id") + "", -1);
            for (Map countMap : countList) {
                Integer _id = Tools.getInt(countMap.get("id") + "", -11);
                if (id == _id) {
                    Integer count = Tools.getInt(countMap.get("count") + "", 0);
                    if (count >= 1) {
                        returnMap.put("has_user", 1);
                    } else {
                        returnMap.put("has_user", 0);
                    }
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                returnMap.put("has_user", 0);
            }
        }
        return returnList;
    }

    /**
     * 查看标签下的成员数
     * @param hospital
     * @param labelId: 标签id，0: 全部标签
     * @return
     */
    public static List<Map> getCountInLabel(Integer hospital, Integer labelId) {
        List<Map> returnList = null;
        if (hospital == null) {
            return returnList;
        }
        labelId = Tools.getInt(labelId, ZERO);
        Where where = new Where();
        if (labelId != 0) {
            where.and("hl.id=", labelId);
        }
        returnList = QBuilder.db("basedb").select("new map(hl.id as id, count(hlm.id) as count)").from("HospitalLabelMember hlm, HospitalLabel hl").where(where.and("hlm.labelId=hl.id").and("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE)).group("hl.id order by hl.id asc").query().getResultObj();
        return returnList;
    }

    /**
     * 查看科室里的人数
     * @param hospital
     * @param deptId: 科室id，0: 全部科室
     * @return
     */
    public static List<Map> getCountInDept(Integer hospital, Integer deptId) {
        List<Map> returnList = null;
        if (hospital == null) {
            return returnList;
        }
        deptId = Tools.getInt(deptId, ZERO);
        Where where = new Where();
        if (deptId != 0) {
            where.and("d.id=", deptId);
        }
        returnList = QBuilder.db("basedb").select("new map(d.id as id, count(hdu.id) as count)").from("HospitalDeptUser hdu, Dept d").where(where.and("hdu.deptId=d.id").and("hdu.hospital=", hospital).and("hdu.status=", ConstantUtil.STATUS_ENABLE).and("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("d.type=", ConstantUtil.DEPT_LINK)).group("d.id").query().getResultObj();
        return returnList;
    }

    /**
     * 查询科室下的子科室
     * @param hospital
     * @return
     */
    public static List<Map> getSubDeptCount(Integer hospital) {
        List<Map> returnList = null;
        if (hospital == null) {
            return returnList;
        }
        returnList = QBuilder.db("basedb").select("new map(d.id as id, d.parent as parent)").from("Dept d").where(new Where("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("d.type=", ConstantUtil.DEPT_LINK)).query().getResultObj();
        if (returnList == null || returnList.isEmpty()) {
            return returnList;
        }
        for (Map deptMap : returnList) {
            Integer id = Tools.getInt(deptMap.get("id") + "", -1);
            for (Map _deptMap : returnList) {
                Integer parent = Tools.getInt(_deptMap.get("parent") + "", -11);
                if (id.equals(parent)) {
                    List<Map> subDeptList = (List<Map>)deptMap.get("sub_dept");
                    if (subDeptList == null) {
                        subDeptList = new ArrayList<Map>();
                        deptMap.put("sub_dept", subDeptList);
                    }
                    subDeptList.add(_deptMap);
                }
            }
        }
        for (Map deptMap : returnList) {
            List<Map> subDeptList = (List<Map>)deptMap.get("sub_dept");
            if (subDeptList == null || subDeptList.isEmpty()) {
                deptMap.put("count", 0);
            } else {
                deptMap.put("count", subDeptList.size());
            }
        }
        return returnList;
    }

    /**
     * 获取hospital医院大标签labelCategory下的有关userId的标签名
     * @param hospital
     * @param labelCategory
     * @param userId: 0 全部用户
     * @return
     */
    public static Map<Integer, List<String>> getTitle(Integer hospital, Integer labelCategory, Integer userId) {
        Map<Integer, List<String>> returnMap = new HashMap<Integer, List<String>>();
        if (hospital == null || labelCategory == null) {
            return returnMap;
        }
        userId = Tools.getInt(userId, 0);
        Where where = new Where();
        if (userId != 0) {
            where.and("hlm.memberId=", userId);
        }
        List<Map> memberList = QBuilder.db("basedb").select("new map(hlm.memberId as user_id, hl.name as title)").from("HospitalLabelCategory hlc, HospitalLabel hl, HospitalLabelMember hlm").where(where.and("hlc.hospital=", "0").and("hlc.status=", ConstantUtil.STATUS_ENABLE).and("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("hl.category=hlc.id").and("hlc.id=", labelCategory).and("hlm.labelId=hl.id").and("hlm.type=1")).order("hlm.id", "asc").query().getResultObj();
        if (memberList != null && !memberList.isEmpty()) {
            for (Map memberMap : memberList) {
                Integer _userId = Tools.getInt(memberMap.get("user_id") + "", -1);
                String title = Tools.getDesc(memberMap.get("title"), "");
                List<String> titleList = returnMap.get(_userId);
                if (titleList == null) {
                    titleList = new ArrayList<String>();
                    returnMap.put(_userId, titleList);
                }
                titleList.add(title);
            }
        }
        return returnMap;
    }

    /**
     * 拼接List中的元素
     * @param list
     * @param key
     * @param <T>
     * @return
     */
    public static <T> String joint(List<T> list, String key) {
        String returnStr = null;
        if (list == null || list.isEmpty()) {
            return returnStr;
        }
        key = Tools.getDesc(key , "");
        StringBuffer stringBuffer = new StringBuffer();
        for (T t : list) {
            String tStr = Tools.getDesc(t, "");
            stringBuffer.append(tStr);
            stringBuffer.append(key);
        }
        returnStr = stringBuffer.substring(0, stringBuffer.length() - key.length());
        return returnStr;
    }

    /**
     * 获取标签成员
     * @param hospital
     * @param labelId: 标签id
     * @param type: 成员类别: 0 全部, 1 成员, 2 部门
     * @return
     */
    public static Map<String, List<Map>> getLabelMember(Integer hospital, Integer labelId, Integer type){
        Map<String, List<Map>> returnMap = new HashMap<String, List<Map>>();
        if (hospital == null || labelId == null) {
            return returnMap;
        }
        type = Tools.getInt(type, ZERO);
        if (type != 2) {
            List<Map> userList = QBuilder.db("basedb").select("new map(hu.id as user_id, hu.employeeId as employee_id, hu.name as name, hu.phone as phone, hu.avatar as avatar, hu.hidden as is_hidden, hu.gender as gender)").from("HospitalLabelMember hlm, HospitalUser hu").where(new Where("hlm.memberId=hu.id").and("hlm.type=1").and("hlm.labelId=", labelId).and("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE)).order("hlm.id", "asc").query().getResultObj();
            if (userList != null && !userList.isEmpty()) {
                List<Integer> idList = QBuilder.db("basedb").select("hlc.id as id").from("HospitalLabelCategory hlc").where(new Where("hlc.hospital=", "0").and("hlc.status=", ConstantUtil.STATUS_ENABLE).and("hlc.name=", "职位")).order("hlc.id", "desc").limit(1).query().getResultObj();
                if (idList != null && !idList.isEmpty()) {
                    Integer LabelCategory = idList.get(0);
                    Map<Integer, List<String>> titleMap = getTitle(hospital, LabelCategory, 0);
                    for (Map userMap : userList) {
                        Integer userId = Tools.getInt(userMap.get("user_id") + "", -11);
                        List<String> titleList = titleMap.get(userId);
                        userMap.put("title", joint(titleList, " "));
                    }
                }
            }
            returnMap.put("user", userList);
        }
        if (type != 1) {
            List<Map> deptList = QBuilder.db("basedb").select("new map(d.id as dept_id, d.deptName as dept_name)").from("HospitalLabelMember hlm, Dept d").where(new Where("hlm.memberId=d.id").and("hlm.labelId=", labelId).and("hlm.type=2").and("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE)).order("hlm.id", "asc").query().getResultObj();
            if (deptList != null && !deptList.isEmpty()) {
                List<Map> countList = getCountInDept(hospital, 0);
                if (countList == null) {
                    countList = new ArrayList<Map>();
                }
                List<Map> subDeptList = getSubDeptCount(hospital);
                if (subDeptList == null) {
                    subDeptList = new ArrayList<Map>();
                }
                for (Map deptMap : deptList) {
                    boolean userFlag = false;
                    boolean deptFlag = false;
                    Integer deptId = Tools.getInt(deptMap.get("dept_id") + "", -1);
                    for (Map subDeptMap : subDeptList) {
                        Integer _deptId = Tools.getInt(subDeptMap.get("id") + "", -11);
                        if (deptId.equals(_deptId)) {
                            Integer count = Tools.getInt(subDeptMap.get("count") + "", 0);
                            if (count >= 1) {
                                deptMap.put("has_child_dept", 1);
                            } else {
                                deptMap.put("has_child_dept", 0);
                            }
                            deptFlag = true;
                            break;
                        }
                    }
                    for (Map countMap : countList) {
                        Integer _deptId = Tools.getInt(countMap.get("id") + "", -11);
                        if (deptId.equals(_deptId)) {
                            Integer count = Tools.getInt(countMap.get("count") + "", 0);
                            if (count >= 1) {
                                deptMap.put("has_user", 1);
                            } else {
                                deptMap.put("has_user", 0);
                            }
                            userFlag = true;
                            break;
                        }
                    }
                    if (!userFlag) {
                        deptMap.put("has_user", 0);
                    }
                    if (!deptFlag) {
                        deptMap.put("has_child_dept", 0);
                    }
                }
            }
            returnMap.put("dept", deptList);
        }
        return returnMap;
    }

    /**
     * 根据labelName获取HospitalLabel对象
     * @param hospital
     * @param labelName
     * @return
     */
    public static HospitalLabel getHospitalLabelByName(Integer hospital, String labelName) {
        HospitalLabel hospitalLabel = null;
        labelName = Tools.getDesc(labelName, "").trim();
        if (hospital == null || labelName.isEmpty()) {
            return hospitalLabel;
        }
        List<HospitalLabel> HospitalLabelList = QBuilder.db("basedb").select().from("HospitalLabel hl").where(new Where("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hl.name=", labelName)).page(1, 1).query().getResultObj();
        if (HospitalLabelList != null && !HospitalLabelList.isEmpty()) {
            hospitalLabel = HospitalLabelList.get(0);
        }
        return hospitalLabel;
    }

    /**
     * 根据labelId获取HospitalLabel对象
     * @param hospital
     * @param labelId
     * @return
     */
    public static HospitalLabel getHospitalLabelById(Integer hospital, Integer labelId) {
        HospitalLabel hospitalLabel = null;
        if (hospital == null || labelId == null) {
            return hospitalLabel;
        }
        List<HospitalLabel> HospitalLabelList = QBuilder.db("basedb").select().from("HospitalLabel hl").where(new Where("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hl.id=", labelId)).page(1, 1).query().getResultObj();
        if (HospitalLabelList != null && !HospitalLabelList.isEmpty()) {
            hospitalLabel = HospitalLabelList.get(0);
        }
        return hospitalLabel;
    }

    /**
     * 获取所有的科室以及科室下所有的子科室和员工forH5
     * @param hospital
     * @return
     */
    public static List<Map> getDeptMember(Integer hospital) {
        List<Map> list = new ArrayList<Map>();
        List<Map> deptList = QBuilder.db("basedb").select("new map(id as dept_id, deptName as dept_name, parent as parent, 2 as type)").from("Dept").where(new Where("hospital=", hospital).and("status=", ConstantUtil.STATUS_ENABLE).and("type=", ConstantUtil.DEPT_LINK)).query().getResultObj();
        List<Map> deptUserList = QBuilder.db("basedb").select("distinct new map(du.deptId as parent, u.id as dept_id, u.employeeId as employee_id, u.name as name, u.phone as phone, u.avatar as avatar, u.hidden as is_hidden, u.gender as gender, 1 as type)").from("HospitalDeptUser du, HospitalUser u").where(new Where("du.hospital=", hospital).and("du.status=", ConstantUtil.STATUS_ENABLE).and("u.status=", ConstantUtil.STATUS_ENABLE).and("u.hospital=", hospital).and("du.userId=u.id")).query().getResultObj();
        for (int i = 0, length = deptList.size(); i < length; i++) {
            Map deptMap = deptList.get(i);
            if ("-1".equals(deptMap.get("parent"))) {
                list.add(deptMap);
            }
            List userList = (List)deptMap.get("member");
            if (Objects.isNull(userList)) {
                userList = new ArrayList();
                deptMap.put("member", userList);
            }
            Integer deptId = (Integer)deptMap.get("dept_id");
            for (int j = 0, dLength = deptUserList.size(); j < dLength; j++) {
                Map deptUserMap = deptUserList.get(j);
                if (deptId.equals(deptUserMap.get("dept_id"))) {
                    userList.add(deptUserMap);
                }
            }
        }
        childMember(list, deptList);
        return list;
    }

    /**
     * 递归查询科室列表的子科室
     * @param list
     * @param deptList
     * @return
     */
    public static void childMember(List<Map> list, List<Map> deptList) {
        if (Objects.isNull(list) || Objects.isNull(deptList) || list.size() == 0 || deptList.size() == 0)
            return;
        for (int i = 0, length = list.size(); i < length; i++) {
            Map map = list.get(i);
            if (Objects.isNull(map) || (Integer)map.get("type") == 1)
                continue;
            String deptId = Tools.getDesc(map.get("dept_id"), "");
            List memberList = (List)map.get("member");
            if (Objects.isNull(memberList)) {
                memberList = new ArrayList();
                map.put("member", memberList);
            }
            List<Map> childDeptList = new ArrayList<>();
            for (int j = 0, dLength = deptList.size(); j < dLength; j++) {
                Map deptMap = deptList.get(j);
                if (Objects.isNull(deptMap))
                    continue;
                if (deptId.equals(deptMap.get("parent"))) {
                    childDeptList.add(deptMap);
                }
            }
            memberList.addAll(0, childDeptList);
            childMember(memberList, deptList);
        }
    }


    /**
     * 获取所有的科室以及科室下所有的子科室和员工for APP
     * @param hospital
     * @return
     */
    public static List<Map> getDeptAndChildDeptOrUser(Integer hospital) {
        List<Map> list = new ArrayList<Map>();
        List<Map> deptList = QBuilder.db("basedb").select("new map(id as dept_id, deptName as dept_name, parent as parent)").from("Dept").where(new Where("hospital=", hospital).and("status=", ConstantUtil.STATUS_ENABLE).and("type=", ConstantUtil.DEPT_LINK)).query().getResultObj();
        List<Map> deptUserList = QBuilder.db("basedb").select("distinct new map(du.deptId as dept_id, u.id as user_id, u.employeeId as employee_id, u.name as name, u.phone as phone, u.avatar as avatar, u.hidden as is_hidden, u.gender as gender)").from("HospitalDeptUser du, HospitalUser u").where(new Where("du.hospital=", hospital).and("du.status=", ConstantUtil.STATUS_ENABLE).and("u.status=", ConstantUtil.STATUS_ENABLE).and("u.hospital=", hospital).and("du.userId=u.id")).query().getResultObj();
        for (int i = 0, length = deptList.size(); i < length; i++) {
            Map deptMap = deptList.get(i);
            if ("-1".equals(deptMap.get("parent"))) {
                list.add(deptMap);
            }
            List userList = (List)deptMap.get("user");
            if (Objects.isNull(userList)) {
                userList = new ArrayList();
                deptMap.put("user", userList);
            }
            Integer deptId = (Integer)deptMap.get("dept_id");
            for (int j = 0, dLength = deptUserList.size(); j < dLength; j++) {
                Map deptUserMap = deptUserList.get(j);
                if (deptId.equals(deptUserMap.get("dept_id"))) {
                    userList.add(deptUserMap);
                }
            }
        }
        childDept(list, deptList);
        return list;
    }

    /**
     * 递归查询科室列表的子科室
     * @param list
     * @param deptList
     * @return
     */
    public static void childDept(List<Map> list, List<Map> deptList) {
        if (Objects.isNull(list) || Objects.isNull(deptList) || list.size() == 0 || deptList.size() == 0)
            return;
        for (int i = 0, length = list.size(); i < length; i++) {
            Map map = list.get(i);
            if (Objects.isNull(map))
                continue;
            String deptId = Tools.getDesc(map.get("dept_id"), "");
            List childDeptList = (List)map.get("child_dept");
            if (Objects.isNull(childDeptList)) {
                childDeptList = new ArrayList();
                map.put("child_dept", childDeptList);
            }
            for (int j = 0, dLength = deptList.size(); j < dLength; j++) {
                Map deptMap = deptList.get(j);
                if (Objects.isNull(deptMap))
                    continue;
                if (deptId.equals(deptMap.get("parent"))) {
                    childDeptList.add(deptMap);
                }
            }
            childDept(childDeptList, deptList);
        }
    }

    /**
     * 获取所有自定义标签类及其成员for H5
     * @param hospital
     * @return
     */
    public static List<Map> getAllCustomizeLabelAndMember(Integer hospital) {
        Map<String, List<Map>> map = getLabelClass(hospital, 2);
        List<Map> list = null;
        if (Objects.isNull(map)) {
            return list;
        }
        list = map.get("customize");
        if (Objects.nonNull(list) && list.size() > 0) {
            for (int i = 0, length = list.size(); i < length; i++) {
                Map labelMap = list.get(i);
                Map labelMember = getLabelMember(hospital, (Integer)labelMap.get("id"), ZERO);
                List<Map> deptList = null, userList = null;
                if (Objects.nonNull(labelMember)) {
                    deptList = (List<Map>)labelMember.get("dept");
                    if (Objects.isNull(deptList))
                        deptList = new ArrayList<>();
                    else if (deptList.size() > 0) {
                        for (int j = 0, dLength = deptList.size(); j < dLength; j++) {
                            Map deptMap = deptList.get(j);
                            if (Objects.nonNull(deptMap))
                                deptMap.put("type", ConstantUtil.HOSPITAL_LABEL_DEPT);
                        }
                    }
                    userList = (List<Map>)labelMember.get("user");
                    if (Objects.isNull(userList))
                        userList = new ArrayList<>();
                    else if (userList.size() > 0) {
                        for (int j = 0, uLength = userList.size(); j < uLength; j++) {
                            Map userMap = userList.get(j);
                            if (Objects.nonNull(userMap))
                                userMap.put("type", ConstantUtil.HOSPITAL_LABEL_USER);
                        }
                        deptList.addAll(userList);
                    }
                    labelMap.put("member", deptList);
                }
            }
        }
        return list;
    }

    /**
     * 获取所有自定义标签类及其成员for APP
     * @param hospital
     * @return
     */
    public static List<Map> getAllCustomizeLabelAndDeptOrUser(Integer hospital) {
        Map<String, List<Map>> map = getLabelClass(hospital, 2);
        List<Map> list = null;
        if (Objects.isNull(map)) {
            return list;
        }
        list = map.get("customize");
        if (Objects.nonNull(list) && list.size() > 0) {
            for (int i = 0, length = list.size(); i < length; i++) {
                Map labelMap = list.get(i);
                Map labelMember = getLabelMember(hospital, (Integer)labelMap.get("id"), ZERO);
                List<Map> deptList = null, userList = null;
                if (Objects.nonNull(labelMember)) {
                    deptList = (List<Map>)labelMember.get("dept");
                    if (Objects.isNull(deptList))
                        deptList = new ArrayList<>();
                    userList = (List<Map>)labelMember.get("user");
                    if (Objects.isNull(userList))
                        userList = new ArrayList<>();
                    labelMap.put("user", userList);
                    labelMap.put("dept", deptList);
                }
            }
        }
        return list;
    }
}
